#!/usr/bin/env python
#coding=utf-8
import re, sys
import eventlet
from eventlet.green import urllib2


def fetch(ip="218.30.108.232"):
    """利用urllib中的库直接打开"""
    url = "http://ip.qq.com/cgi-bin/searchip"
    data = "searchip1=" + ip
    buf = urllib2.urlopen(url, data).read().decode("gb2312")
    # print url, buf
    return url, buf

def getip_qq(ip="218.30.108.232"):
	'''
	use QQ database
	'''
	#请求URL，以及请求解析的URL格式变化
	url_qq = "http://ip.qq.com/cgi-bin/searchip"
	data = "searchip1=" + ip

	#不同的网站网页字符编码不同，匹配不同的内容，封装不同的编码
	#html = urllib2.urlopen(url_qq, data).read().decode("gb2312")
	url_list = [ip]
	# print html
	#查询匹配的内容
	# pat = re.compile(r'<span>(.*)</span></p>')
	# result = re.findall(pat, html)

	#定义绿色线程池
	pool = eventlet.GreenPool(50)
	list_buf = []
	for url, buf in pool.imap(fetch, url_list):
		# print url, buf
		list_buf.append(buf)

	for buf in list_buf:
		res = re.findall('<a href="(http.*)"', buf)
		# pat = re.compile(r'<span>(.*)</span></p>')
		print res
		# print "ip.qq.com 查询地址："
		# print '    ' + ip + " < --- > " + result[0].encode("utf-8").replace('&nbsp;', '')

if __name__ == '__main__':
	# fetch()
	getip_qq()